#!/usr/bin/env python
#coding:utf-8
from  django.utils import timezone
from repository import models
import random,time,json
from django.utils import timezone

def recent_accssed_hosts(request):
    days_before_14 = timezone.now() + timezone.timedelta(days=-30)
    recent_logins = models.AuditLog.objects.filter(date__gt = days_before_14,user_id=request.user.id,action_type=1).order_by('date')
    unique_bindhost_ids = set([i[0] for i in recent_logins.values_list('host_id')])
    recent_login_hosts = []
    for h_id in unique_bindhost_ids:
        recent_login_hosts.append(recent_logins.filter(host_id=h_id).latest('date'))

    return  set(recent_login_hosts)

class Token(object):
    def __init__(self,request):
        self.request = request
        self.token_type = request.POST.get('token_type')
        self.token = {'token':None}
    def generate(self):
        func = getattr(self,self.token_type)
        return func()

    def host_token(self):
        bind_host_id = self.request.POST.get('bind_host_id')
        host_obj = models.BindHosts.objects.get(id=int(bind_host_id))

        latest_token_obj = models.Token.objects.filter(host_id = int(bind_host_id),user_id=self.request.user.id).last()
        token_gen_flag = False

        if latest_token_obj:

            token_gen_time_stamp = time.mktime(latest_token_obj.date.timetuple())
            current_time = time.mktime(timezone.now().timetuple() )
            if current_time - token_gen_time_stamp >latest_token_obj.expire:#token expired
                token_gen_flag = True
        else:
            token_gen_flag = True

        if token_gen_flag:
            token = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba1234567890',6))
            models.Token.objects.create(
                user = self.request.user,
                host = host_obj,
                token = token
            )
        else:
            token = latest_token_obj.token

        self.token['token'] = token
        return  json.dumps(self.token)

